var histogram;
var allNames = [];
var allNums = [];
var allObj = [];
var total=0;
var params={
    start:0,
    limit:10,
    search: 123223,
    startDate: 0,
    endDate: 0
};
$(function () {
    initDateRangePicker();
    initHistogram();
    loadOption();
});

function initDateRangePicker() {
    var date = new Date();
    if(date.getMonth() > 0) {
        $('input[name="daterange"]').daterangepicker({
                locale: {
                    format: 'YYYY-MM-DD'
                },
                startDate: date.getFullYear() + "-" + formNumber(date.getMonth()) + formNumber(date.getDate()),
                endDate: date.getFullYear() + "-" + formNumber(date.getMonth() + 1) + '-' + formNumber(date.getDate())
            },
            function (start, end, label) {
                //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            });
    } else {
        $('input[name="daterange"]').daterangepicker({
                locale: {
                    format: 'YYYY-MM-DD'
                },
                startDate: date.getFullYear() - 1 + "-" + formNumber(date.getMonth() + 12) + formNumber(date.getDate()),
                endDate: date.getFullYear() + "-" + formNumber(date.getMonth() + 1) + '-' + formNumber(date.getDate())
            },
            function (start, end, label) {
                //                        alert("A new date range was chosen: " + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD'));
            });
    }
}

function clearSelect() {
    var region = $("#region");
    var select = $(".select2-selection__rendered");
    region.find("option:first").prop("selected", 'selected');
    select.text(region.find("option:first").text());
    select.attr("title", region.find("option:first").text());
    initDateRangePicker();
    loadHistogramData();
}

/**
 * 加载地区下拉框数据
 */
function loadOption() {
    var url = baseRegionUrl + "list/region?start=0&limit=10&length=10";
    $.ajax(ajaxCommon.buildLoadingOption({
        url: url,
        headers: {
            "authorization": 'Bearer ' + getCookie(cookieName)
        },
        type: "GET",
        contentType: "application/json",
        success: function (data) {
            var arr = [];
            $(data.data.rows).each(function (index, obj) {
                var region = {"id": obj.id, "text": obj.name};
                arr.push(region);
            });
            $('#region').select2({
                data: arr
            });
            loadHistogramData();
        },
        error: function (request, error) {
            if (request.status === 401) {
                $(location).attr('href', 'login.html');
            } else {
                swal("失败");
            }
        }
    }));
}

/**
 * 加载分页数据
 */
function loadPage() {
    var pageSelect = $("#page");
    pageSelect.empty();
    var page = total / 10;
    for (var i = 0; i < page; i++) {
        var text = (i*10 + 1) + "-" + ((i+1) * 10);
        if (i === 0) {
            pageSelect.append("<option selected value='"+i+"'>" + text + "</option>");
        } else {
            pageSelect.append("<option value='"+i+"'>" + text + "</option>");
        }
    }
}

/**
 * 加载总数据
 */
function loadHistogramData(type) {
    var dateInterval = $("#reservation").val().split(" - ");
    var startDate = Date.parse(dateInterval[0]);
    var endDate = Date.parse(dateInterval[1]);
    params.search=$("#region").val();
    params.startDate=startDate;
    params.endDate=endDate;
    var url = baseQuestionUrl + "list/firstkey";
    ajaxCommon.request('get',url,params,function (data) {
        var names = [];
        var nums = [];
        allNames.splice(0, allNames.length);
        allNums.splice(0, allNums.length);
        total=data.data.total;
        if (!type) {
            loadPage();
        }
        $(data.data.rows).each(function (index, obj) {
            allNames.push(obj.firest);
            allNums.push(obj.count);
            allObj.push(obj)
        });
        for (var i = 0; i < allNames.length; i++) {
            if (i <= 9) {
                names.push(allNames[i]);
            } else {
                break;
            }
        }
        for (var j = 0; j < allNums.length; j++) {
            if (j <= 9) {
                nums.push(allNums[j]);
            } else {
                break;
            }
        }
        // 将数据载入柱状图
        histogram.setOption({
            xAxis: {
                data: names
            },
            series: [{
                name: '次数',
                data: nums
            }]
        });
        // 将数据载入表格
        loadTable(0);
    })
}

/**
 * 加载表格数据
 * @param startIndex
 */
function loadTable(startIndex) {
    var rank = $("#rank");
    var keyword = $("#keyword");
    var num = $("#num");
    rank.empty();
    keyword.empty();
    num.empty();
    keyword.append("<td>关键词</td>");
    num.append("<td>次数</td>");
    var index;
    if (startIndex + 10 < allNames.length && startIndex + 10 < allNums.length) {
        index = startIndex + 10;
    } else {
        index = allNames.length;
    }
    for (var i = startIndex; i < index; i++) {
        var keywordTd = "<td>" + allNames[i] + "</td>";
        var numTd = "<td>" + allNums[i] + "</td>";
        keyword.append($(keywordTd));
        num.append($(numTd));
    }
}

/**
 * 初始化柱状图
 */
function initHistogram() {
    // app.title = '坐标轴刻度与标签对齐';
    var option = {
        title: {
            text: '数量统计',
            left: 50
        },
        color: ['#3398DB'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [
            {
                type: 'category',
                // data: ['价格', '安全', '优惠', '配置', '外形', '舒适', '油耗', '活动', '内饰', '保养'],
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: 20
                },
            }
        ],
        yAxis: [
            {
                type: 'value'
            }
        ],
        series: [
            {
                name: '次数',
                type: 'bar',
                barWidth: '60%'/*,
                data: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]*/
            }
        ]
    };
    histogram = echarts.init(document.getElementById("histogram"));
    histogram.setOption(option);
}

/**
 * 导出Excel
 */
function exportExcel() {
    if (allObj.length <= 0) {
        swal("当前数据为空");
        return;
    }
    var sheetData = [];
    $(allObj).each(function (index, obj) {
        var date = formatDate(new Date, obj.created);
        var d = {
            "index": index + 1,
            "keyword": obj.firest,
            "num": obj.count
        };
        sheetData.push(d);
    });
    var option = {};
    option.fileName = "首问题关键字(" + $("#reservation").val().split(" - ") + ")";
    option.datas = [
        {
            sheetData: sheetData,
            sheetName: 'oftenKeywordQuestion',
            sheetFilter: ['index', 'keyword', "num"],
            sheetHeader: ['排名', '关键字', '次数']
        },
        {
            sheetData: sheetData
        }
    ];
    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
}

/**
 * 切换分页
 */
function changePage() {
    params.start=$('#page').val()*10;
    loadHistogramData(params.start);
}
